package com.javasea.orm.dynamicDS.config;

import com.javasea.orm.dynamicDS.tenant.TenantContext;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MultitenantDataSource extends AbstractRoutingDataSource {
    /**
     * determineCurrentLookupKey方法里面有一个resolvedDataSources的Map，存储了多个DataSource，会调用determineCurrentLookupKey()来Runtime决定使用哪个DataSource，如果没有指定的那个Key，那么就会使用DefaultDataSource
     * 所以使用它就是需要
     * - Override determineCurrentLookupKey()方法，定义tenantId作为key
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return TenantContext.getCurrentTenant();
    }

    private ConcurrentHashMap<String, DataSource> backupTargetDataSources = new ConcurrentHashMap<>();

    /**
     * 调用setTargetDataSources方法去把Map填进去
     * @param key
     * @param ds
     */
    public void addDataSourceToTargetDataSource(String key ,DataSource ds){
        this.backupTargetDataSources.put(key, ds);
        this.setTargetDataSource(this.backupTargetDataSources);
    }


    public void setTargetDataSource(Map targetDataSource){
        super.setTargetDataSources(targetDataSource);
        this.afterPropertiesSet();
    }
}
